<template>
  <div
    ref="custom-table"
    class="custom-table-container"
    :class="{ 'vab-fullscreen': isFullscreen }"
  >
    <vab-query-form>
      <vab-query-form-top-panel>
        <el-form
          ref="form"
          :inline="true"
          label-width="80px"
          :model="queryForm"
          @submit.native.prevent
        >
          <el-form-item label="访客姓名" prop="condition.name">
            <el-input
              v-model="queryForm.condition.name"
              clearable
              placeholder="请输入访客姓名"
            />
          </el-form-item>
          <el-form-item label="邀请人" prop="condition.inviteeName">
            <el-input
              v-model="queryForm.condition.inviteeName"
              clearable
              placeholder="请输入邀请人"
            />
          </el-form-item>
          <el-form-item label="证件号码" prop="condition.certNo">
            <el-input
              v-model="queryForm.condition.certNo"
              clearable
              placeholder="请输入证件号码"
            />
          </el-form-item>
          <el-form-item v-show="!fold" label="手机号码" prop="condition.phone">
            <el-input
              v-model="queryForm.condition.phone"
              clearable
              placeholder="请输入手机号码"
            />
          </el-form-item>
          <el-form-item v-show="!fold" label="小区编号" prop="condition.areaNo">
            <el-select
              v-model="queryForm.condition.areaNo"
              class="full-select"
              clearable
              placeholder="请选择小区编号"
            >
              <el-option
                v-for="item in cellCode"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button
              icon="el-icon-search"
              native-type="submit"
              type="primary"
              @click="handleQuery"
            >
              查询
            </el-button>
            <el-button icon="el-icon-refresh-left" @click="resetQuery">
              重置
            </el-button>
            <el-button type="text" @click="handleFold">
              <span v-if="fold">展开</span>
              <span v-else>合并</span>
              <vab-icon
                class="vab-dropdown"
                :class="{ 'vab-dropdown-active': fold }"
                icon="arrow-up-s-line"
              />
            </el-button>
          </el-form-item>
        </el-form>
      </vab-query-form-top-panel>
      <vab-query-form-left-panel :lg="12" :md="12" :sm="12" :xl="12" :xs="12">
        <!--        <el-button icon="el-icon-plus" type="primary" @click="handleEdit">-->
        <!--          新增居民-->
        <!--        </el-button>-->
      </vab-query-form-left-panel>
      <vab-query-form-right-panel :lg="12" :md="12" :sm="12" :xl="12" :xs="12">
        <el-button
          style="margin: 0 10px 10px 0 !important"
          type="primary"
          @click="clickFullScreen"
        >
          <vab-icon
            :icon="isFullscreen ? 'fullscreen-exit-fill' : 'fullscreen-fill'"
          />
          表格全屏
        </el-button>
        <el-popover
          ref="popover"
          popper-class="custom-table-checkbox"
          trigger="hover"
        >
          <el-radio-group v-model="lineHeight">
            <el-radio label="medium">大</el-radio>
            <el-radio label="small">中</el-radio>
            <el-radio label="mini">小</el-radio>
          </el-radio-group>
          <template #reference>
            <el-button style="margin: 0 10px 10px 0 !important" type="primary">
              <vab-icon icon="line-height" />
              表格尺寸
            </el-button>
          </template>
        </el-popover>
        <el-popover popper-class="custom-table-checkbox" trigger="hover">
          <el-checkbox-group v-model="checkList">
            <vab-draggable v-bind="dragOptions" :list="columns">
              <div v-for="(item, index) in columns" :key="item + index">
                <vab-icon icon="drag-drop-line" />
                <el-checkbox
                  :disabled="item.disableCheck === true"
                  :label="item.label"
                >
                  {{ item.label }}
                </el-checkbox>
              </div>
            </vab-draggable>
          </el-checkbox-group>
          <template #reference>
            <el-button
              icon="el-icon-setting"
              style="margin: 0 0 10px 0 !important"
              type="primary"
            >
              可拖拽列设置
            </el-button>
          </template>
        </el-popover>
      </vab-query-form-right-panel>
    </vab-query-form>

    <el-table
      ref="tableSort"
      v-loading="listLoading"
      :border="border"
      :data="list"
      :size="lineHeight"
      :stripe="stripe"
      @selection-change="setSelectRows"
    >
      <el-table-column
        align="center"
        label="序号"
        show-overflow-tooltip
        width="95"
      >
        <template #default="{ $index }">
          {{ $index + 1 }}
        </template>
      </el-table-column>
      <el-table-column
        v-for="(item, index) in finallyColumns"
        :key="index"
        align="center"
        :label="item.label"
        :width="item.width"
      >
        <template #default="{ row }">
          <template v-if="item.label.indexOf('头像') > -1">
            <el-image
              :preview-src-list="imageList"
              :src="baseUrl + row[item.prop]"
            />
          </template>
          <template v-else-if="item.label === '人员类型'">
            <span>{{ userType[row[item.prop]] || '-' }}</span>
          </template>
          <template v-else-if="item.label === '授权类型'">
            <span>{{ authType[row[item.prop]] || '-' }}</span>
          </template>
          <template v-else-if="item.dict">
            <DictListItem :dict-key="item.dict" :dict-val="row[item.prop]" />
          </template>
          <span v-else>{{ row[item.prop] || '-' }}</span>
        </template>
      </el-table-column>
      <!--      <el-table-column-->
      <!--        align="center"-->
      <!--        fixed="right"-->
      <!--        label="操作"-->
      <!--        show-overflow-tooltip-->
      <!--        width="150"-->
      <!--      >-->
      <!--        <template #default="{ row }">-->
      <!--          &lt;!&ndash;          <el-button type="text" @click="auditInfo(row)">查看</el-button>&ndash;&gt;-->
      <!--          <el-button-->
      <!--            v-permissions="['SUPER']"-->
      <!--            type="text"-->
      <!--            @click="handleDelete(row)"-->
      <!--          >-->
      <!--            删除-->
      <!--          </el-button>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <template #empty>
        <el-image
          class="vab-data-empty"
          :src="require('@/assets/empty_images/data_empty.png')"
        />
      </template>
    </el-table>
    <el-pagination
      background
      :current-page="queryForm.pageNum"
      :layout="layout"
      :page-size="queryForm.pageSize"
      :total="total"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    />
    <north-resident ref="edit" @fetch-data="fetchData" />
  </div>
</template>

<script>
  import {
    getNorthGuestList,
    deleteNorthGuestById,
    exportResident,
    uploadResidentUrl,
    downloadTemplateUrl,
  } from '@/api/resident'
  import DictListItem from '../components/DictListItem'
  import NorthResident from '../components/NorthResident'
  import { baseURL, picBaseUrl } from '@/config'
  import VabDraggable from 'vuedraggable'
  import { mapGetters } from 'vuex'

  export default {
    name: 'NorthGuestList',
    components: {
      NorthResident,
      VabDraggable,
      DictListItem,
    },
    data() {
      return {
        baseUrl: picBaseUrl,
        upResidentToServer: baseURL + uploadResidentUrl,
        isUploading: false,
        isFullscreen: false,
        isDownloading: false,
        border: true,
        fold: true,
        height: this.$baseTableHeight(1),
        stripe: false,
        lineHeight: 'medium',
        checkList: [
          '访客姓名',
          '证件类型',
          '证件号码',
          '手机号码',
          '头像',
          '邀请人',
          '访客类型',
          '小区编码',
          '授权开始时间',
          '授权结束时间',
          '创建时间',
        ],
        columns: [
          {
            label: '访客姓名',
            width: '100',
            prop: 'name',
            sortable: false,
            disableCheck: true,
          },
          {
            label: '证件类型',
            width: '150',
            prop: 'certType',
            sortable: false,
            dict: 'certType',
          },
          {
            label: '证件号码',
            width: '200',
            prop: 'certNo',
            sortable: false,
          },
          {
            label: '手机号码',
            width: '150',
            prop: 'phone',
            sortable: false,
          },
          {
            label: '头像',
            width: '100',
            prop: 'photo',
            sortable: false,
          },
          {
            label: '邀请人',
            width: '100',
            prop: 'inviteeName',
            sortable: false,
          },
          {
            label: '访客类型',
            width: '100',
            prop: 'typeDsc',
            sortable: false,
          },
          {
            label: '小区编码',
            width: '150',
            prop: 'areaName',
            sortable: false,
          },
          {
            label: '访问开始时间',
            width: '150',
            prop: 'startDate',
            sortable: false,
          },
          {
            label: '访问结束时间',
            width: '150',
            prop: 'endDate',
            sortable: false,
          },
          {
            label: '创建时间',
            width: '200',
            prop: 'createTime',
            sortable: false,
          },
        ],
        userType: {
          1: '业主',
          2: '租户',
          3: '其他',
          4: '工作人员',
          5: '访客',
        },
        authType: {
          1: '有效',
          2: '永久',
        },
        list: [],
        imageList: [],
        listLoading: true,
        isExporting: false,
        layout: 'total, sizes, prev, pager, next, jumper',
        total: 0,
        selectRows: '',
        queryForm: {
          condition: {
            orderBy: 'id',
            orderDirect: 'desc',
            name: null,
            inviteeName: null,
            certNo: null,
            areaNo: null,
            phone: null,
            sex: null,
          },
          pageNum: 1,
          pageSize: 10,
          title: '',
        },
      }
    },
    computed: {
      ...mapGetters({
        certType: 'dict/certType',
        countryList: 'dict/countryList',
        auditStatus: 'dict/auditStatus',
        cellCode: 'dict/cellCode',
        policyRole: 'dict/policyRole',
        nationList: 'dict/nationList',
        sexType: 'dict/sexType',
        token: 'user/token',
      }),
      dragOptions() {
        return {
          animation: 600,
          group: 'description',
        }
      },
      finallyColumns() {
        return this.columns.filter((item) =>
          this.checkList.includes(item.label)
        )
      },
    },
    created() {
      this.fetchData()
    },
    methods: {
      doCommand(cmd) {
        if (cmd === 'a') {
          this.downloadTemp()
        } else if (cmd === 'b') {
          this.showOverSeven()
        }
      },
      showOverSeven() {
        const overRef = this.$refs['overSevenRef']
        if (overRef) {
          overRef.showEdit()
        }
      },
      downloadTemp() {
        this.$refs['down_load_frame'].src =
          this.baseUrl + downloadTemplateUrl + '?random=' + Date.now()
        setTimeout(() => {
          this.$refs['down_load_frame'].src = ''
        }, 100)
      },
      beforeUpload() {
        this.isUploading = true
      },
      handleAvatarSuccess(res) {
        if (res && res.status === 0) {
          this.$baseMessage(
            `导入结果，\n成功：${res.successCount || 0}条，失败：${
              res.errorCount || 0
            }条`,
            'success',
            'vab-hey-message-success'
          )
          if (res.errorCount > 0 && res.filePath) {
            this.$refs['down_load_frame'].src = this.baseUrl + res.filePath
            setTimeout(() => {
              this.$refs['down_load_frame'].src = ''
            }, 100)
          }
        } else {
          this.$baseMessage(
            res ? res.msg : '数据导入失败！',
            'error',
            'vab-hey-message-error'
          )
        }
        this.isUploading = false
      },
      handleError() {
        this.$baseMessage('数据导入失败！', 'error', 'vab-hey-message-error')
        this.isUploading = false
      },
      exportData() {
        this.isExporting = true
        exportResident()
          .then((res) => {
            if (res && res.status === 0) {
              this.$baseMessage(
                '数据导出成功！',
                'success',
                'vab-hey-message-success'
              )
              this.$refs['down_load_frame'].src = this.baseUrl + res.data
              setTimeout(() => {
                this.$refs['down_load_frame'].src = ''
              }, 100)
            } else {
              this.$baseMessage(
                res ? res.msg : '数据导出失败！',
                'error',
                'vab-hey-message-error'
              )
            }
          })
          .catch((err) => {
            console.log(err)
            this.$baseMessage(
              '导出失败，请重试！',
              'error',
              'vab-hey-message-error'
            )
          })
          .then(() => {
            this.isExporting = false
          })
      },
      clickFullScreen() {
        this.isFullscreen = !this.isFullscreen
        this.handleHeight()
      },
      handleFold() {
        this.fold = !this.fold
        this.handleHeight()
      },
      handleHeight() {
        if (this.isFullscreen) this.height = this.$baseTableHeight(1) + 210
        else this.height = this.$baseTableHeight(1)
      },
      setSelectRows(val) {
        this.selectRows = val
      },
      handleSizeChange(val) {
        this.queryForm.pageSize = val
        this.fetchData()
      },
      handleCurrentChange(val) {
        this.queryForm.pageNum = val
        this.fetchData()
      },
      handleQuery() {
        this.queryForm.pageNum = 1
        this.fetchData()
      },
      resetQuery() {
        this.$refs['form'].resetFields()
        this.queryForm.pageNum = 1
        this.fetchData()
      },
      previewUrl(row) {
        console.log(row)
      },
      watchUrl(row) {
        console.log(row)
      },
      outputResidents() {
        console.log('output residents')
      },
      handleEdit(row) {
        if (row && row.id) {
          this.$refs['edit'].showEdit(row)
        } else {
          this.$refs['edit'].showEdit()
        }
      },
      auditInfo(row) {
        this.$refs['edit'].showEdit(row)
      },
      handleDelete(row) {
        console.log(row)
        this.$baseConfirm('确定要删除当前项吗', null, async () => {
          try {
            const res = await deleteNorthGuestById(row.id)
            if (res && res.status === 0) {
              this.$baseMessage(
                '删除成功！',
                'success',
                'vab-hey-message-success'
              )
              await this.fetchData()
            } else {
              this.$baseMessage(
                res ? res.msg : '删除失败！',
                'error',
                'vab-hey-message-error'
              )
            }
          } catch (e) {
            console.log(e)
            this.$baseMessage(
              e ? e.message : '删除失败！',
              'error',
              'vab-hey-message-error'
            )
          }
        })
      },
      async fetchData() {
        this.listLoading = true
        try {
          const res = await getNorthGuestList(this.queryForm)
          if (res && res.data) {
            const { list, total } = res.data
            this.list = list || []
            const imageList = []
            list.forEach((item) => {
              item.photo && imageList.push(this.baseUrl + item.photo)
            })
            this.imageList = imageList
            this.total = total
          }
        } catch (e) {
          console.log(e)
        }
        this.listLoading = false
      },
    },
  }
</script>

<style lang="scss" scoped>
  .custom-table-container {
    ::v-deep {
      i {
        cursor: pointer;
      }
    }

    .stripe-panel,
    .border-panel {
      margin: 0 10px $base-margin/2 10px !important;
    }
  }
</style>
<style lang="scss">
  .custom-table-checkbox {
    [class*='ri'] {
      vertical-align: -2.5px;
      cursor: pointer;
    }

    .el-checkbox {
      margin: 5px 0 5px 8px;
    }
  }
  .resident-uploader .el-upload > button {
    //border: 1px dashed #d9d9d9;
    //border-radius: 6px;
    //cursor: pointer;
    //position: relative;
    //overflow: hidden;
    margin: 0 10px 10px 0 !important;
  }
  .drop-box {
    margin: 0 10px 10px 0 !important;
  }
</style>
